//
//  JTSeeBigPictureViewController.m
//  百思不得姐
//
//  Created by Robin Zhang on 2017/1/15.
//  Copyright © 2017年 BeiJingWangDianJieTong. All rights reserved.
//

#import "JTSeeBigPictureViewController.h"
#import <UIImageView+WebCache.h>
#import "JTTopic.h"
#import <SVProgressHUD.h>

/** 保存图片 */
//#import <AssetsLibrary/AssetsLibrary.h> // iOS9.0之后废弃
#import <Photos/Photos.h> // iOS9.0开始推荐

@interface JTSeeBigPictureViewController () <UIScrollViewDelegate>

/** 图片空间 */
@property (nonatomic, weak) UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;

@end

@implementation JTSeeBigPictureViewController

static NSString *JTAssetCollectionTitle;

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    JTAssetCollectionTitle = [[NSBundle mainBundle].infoDictionary objectForKey:(NSString *)kCFBundleExecutableKey];
    
    /* 1.UIScrollView */
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:JTScreenBounds];
    [scrollView setDelegate:self];
    [self.view insertSubview:scrollView atIndex:0];
    
    /* 2.UIImageView */
    UIImageView *imageView = [[UIImageView alloc] init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.topic.largeImage] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        if (image == nil) {
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"图片加载失败！\nerror:%ld", error.code]];
            [SVProgressHUD dismissWithDelay:2];
            return;
        }
        [self.saveButton setEnabled:YES];
    }];
    [scrollView addSubview:imageView];
    
    [imageView setJt_width:scrollView.jt_width];
    [imageView setJt_height:self.topic.height * (imageView.jt_width / self.topic.width)];
    [imageView setJt_x:0];
    
    // 如果图片高度超过整个屏幕
    if (imageView.jt_height > JTScreenHeight) {
        
        [imageView setJt_y:0];
        // 滚动范围
        [scrollView setContentSize:CGSizeMake(0, imageView.jt_height)];
    }
    else {
        
        [imageView setJt_centerY:scrollView.jt_height * 0.5];
    }
    
    [self setImageView:imageView];
    
    // 设置缩放比例(就是两指放大缩小的功能；最大的放大情况就是image的原大小)
    CGFloat scale = self.topic.width / imageView.jt_width;
    if (scale > 1.0) {
        
        [scrollView setMaximumZoomScale:scale];
        // default is 1.0. must be > minimum zoom scale to enable zooming
        // minimum zoom scale: default is 1.0
    }
}

/** 转变电源条颜色(白色) */
- (UIStatusBarStyle)preferredStatusBarStyle {
    
    return UIStatusBarStyleLightContent;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - <UIScrollViewDelegate>
/** 返回支持两指放大缩小的控件 */
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    
    return self.imageView;
}

/** 当手指停止放大缩小时调用 */
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
    
    /**
     scrollView.contentSize:
     width会自动设置；
     height需要判断
     */
    if (view.jt_height > scrollView.jt_height) {
        
        CGSize contentSize = scrollView.contentSize;
        contentSize.height = view.jt_height;
        [scrollView setContentSize:contentSize];
        view.jt_y = 0;
    }
    else {
    
        CGSize contentSize = scrollView.contentSize;
        contentSize.height = 0;
        [scrollView setContentSize:contentSize];
        [view setJt_centerY:scrollView.jt_height * 0.5];
    }
}

#pragma mark - 监听
- (IBAction)back:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)save:(UIButton *)sender {
    
    /**
     PHAuthorizationStatusNotDetermined = 0, // 用户还没做出选择
     PHAuthorizationStatusDenied,            // 用户拒绝当前应用访问相册(用户当初点击了“不允许”)
     PHAuthorizationStatusAuthorized         // 用户允许当前应用访问相册(用户当初点击了好许”)
     PHAuthorizationStatusRestricted,        // 由于“家长控制”，导致应用无法访问“相册”(跟用户的选择没有限制)
     */
    
    // 判断授权状态
    switch ([PHPhotoLibrary authorizationStatus]) { // 1.由于“家长控制”，导致应用无法访问“相册”(跟用户的选择没有限制)
        case PHAuthorizationStatusRestricted:
            [SVProgressHUD showErrorWithStatus:@"由于系统原因，无法访问相册！"];
            [SVProgressHUD dismissWithDelay:2];
            break;
            
        case PHAuthorizationStatusDenied: // 2.用户拒绝当前应用访问相册(用户当初点击了“不允许”)
            JTLog(@"提醒用户去[设置-隐私-照片-XXXX]打开访问开关");
            break;

        case PHAuthorizationStatusAuthorized: // 3.用户允许当前应用访问相册(用户当初点击了好许”)
            
            [self saveImage];
            break;
            
        case PHAuthorizationStatusNotDetermined: { // 4.用户还没做出选择
            
            JTWeak(self)
            // 弹框请求用户授权
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                
                if (status == PHAuthorizationStatusAuthorized) { // 用户点击了“好”
                    
                    [weak_self saveImage];
                }
            }];
            break;
        }
    }
}

/** 保存图片 */
- (void)saveImage {
    
    [SVProgressHUD show];
    [self.saveButton setEnabled:NO];
    
    /**
     PHAsset:一个资源，比如一张图片\一段视频
     PHAssetCollection:一个相簿
     */
    
    // PHAsset的标识，利用这个标识可以找到相应的PHAsset对象(图片对象)
    __block NSString *assetLocalIdentifier = nil;
    
    // 如果想对“相册”进行修改(增删改)，那么修改代码必须放在[PHPhotoLibrary sharedPhotoLibrary]的performChanges方法的block中
    PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
    
    // 1.保存图片A到“相机胶卷”中
    [library performChanges:^{ /** 一.异步执行block */
    
        // 创建图片的请求(一旦执行这一句已经开始保存了；返回值暂时用不到)
        assetLocalIdentifier = [PHAssetCreationRequest creationRequestForAssetFromImage:self.imageView.image].placeholderForCreatedAsset.localIdentifier;
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        
        if (success == NO) { // 保存失败
           
            [self showErrorWithStatus:@"保存[图片]到[相机胶卷]中失败！" error:error];
            return;
        }
        
        // 2.获得相簿
        PHAssetCollection *createdAssetCollection = [self createdAssetCollection];
        if (!createdAssetCollection) return; 
        
        // 3.添加“相机胶卷”中的图片A到新建的“相簿”D中
        [library performChanges:^{ /** 三.异步执行block */
            
            // 获得图片
            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
            
            // 添加图片到相簿中的请求
            PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdAssetCollection];
            
            // 添加图片到相簿
            [request addAssets:@[asset]];
            
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            
            if (success) { // 保存成功
                
                [self showSuccessWithStatus:@"成功添加[相片]到[相簿]！"];
            }
            else {
                
                [self showErrorWithStatus:@"添加[图片]到[相簿]失败！" error:error];
            }
        }];
    }];
}


/**
 获得相簿(有则获取已创建的；没有则创建一个相簿)
 */
- (PHAssetCollection * _Nullable)createdAssetCollection {
    
    /** 1.从已存在相簿中查找这个应用对应的相簿 */
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    for (PHAssetCollection *collection in assetCollections) {
        
        if ([collection.localizedTitle isEqualToString:JTAssetCollectionTitle]) {
            
            return collection;
        }
    }
    
    /** 2.没有找到相应的相簿，得创建新的相簿 */
    // PHAssetCollection的标识，利用这个标识可以找到相应的PHAssetCollection对象(相簿对象)
    __block NSString *assetCollectionLocalIdentifier = nil;
    
    
    // 错误信息
    NSError *error = nil;
    
    /** 在当前线程执行Block */
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        
        // 创建“相簿”的请求
        assetCollectionLocalIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:JTAssetCollectionTitle].placeholderForCreatedAssetCollection.localIdentifier;
        
    } error:&error];
    
    // 如果有错误信息
    if (error) {
        
        [self showErrorWithStatus:@"创建相簿失败！" error:error];
        return nil;
    }
    
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[assetCollectionLocalIdentifier] options:nil].lastObject;
}

- (void)showSuccessWithStatus:(NSString *)status {
    
    JTWeak(self)
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [weak_self.saveButton setEnabled:YES];
        
        [SVProgressHUD dismiss];
        [SVProgressHUD showSuccessWithStatus:status];
        [SVProgressHUD dismissWithDelay:2];
    });
}

- (void)showErrorWithStatus:(NSString *)status error:(NSError * _Nonnull)error {
    
    JTWeak(self)
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [weak_self.saveButton setEnabled:YES];
        
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@\nerror:%ld", status, error.code]];
        [SVProgressHUD dismissWithDelay:2];
    });
}

@end
